package org.esgi.transformer.impl;

import org.esgi.model.interfaces.IAnswer;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLHistoryAnswerTransformer extends XMLAnswerTransformer
{
	public static final String XMLHistoryAnswerIsSelectedNodeName = "selected";
	
	@Override
	public IAnswer answerFromElement(Element e) 
	{
		IAnswer answer = super.answerFromElement(e);
		NodeList nl = e.getChildNodes();
		for(int i=0 ; i<nl.getLength(); i++)
		{
			Node childNode = nl.item(i);
			if(childNode.getNodeName().equals(this.addDefaultNamespaceToName(XMLHistoryAnswerIsSelectedNodeName)))
			{
				Node textNode = childNode.getFirstChild();
				if(textNode != null)
				{
					answer.setIsSelected(Boolean.parseBoolean(textNode.getNodeValue()));
				}
			}
		}
		return answer;
	}
	
	@Override
	public Element answerToElement(IAnswer anAnswer, Document doc)
	{
		Element answerNode = super.answerToElement(anAnswer, doc);
		if(answerNode != null)
		{
			Element selectedNode = doc.createElement(this.addDefaultNamespaceToName(XMLHistoryAnswerIsSelectedNodeName));
			selectedNode.appendChild(doc.createTextNode(new Boolean(anAnswer.getIsSelected()).toString()));
			answerNode.appendChild(selectedNode);
		}
		return answerNode;
	}
}
